from PyQt5.QtWidgets import QWidget, QVBoxLayout, QGraphicsView, QGraphicsScene, QLabel, QHBoxLayout, QPushButton
from PyQt5.QtCore import Qt, QRectF, QTimer
from PyQt5.QtGui import QPixmap, QPainter

class ImageView(QWidget):
    def __init__(self, title):
        super().__init__()
        self.title = title
        self.scale_factor = 1.0
        self.current_pixmap = None  # 当前显示的图像缓存
        # 新增图像列表和索引变量
        self.rgb_image_list = []
        self.ti_image_list = []
        self.image_index = 0
        self._init_ui()

    def _init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)  # 去除边距
        
        # 标题标签
        title_label = QLabel(self.title)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("font-size: 14px; font-weight: bold; padding: 5px;")
        layout.addWidget(title_label)
        
        # 新增：导航与缩放按钮布局
        nav_layout = QHBoxLayout()
        btn_zoom_in = QPushButton("放大")
        btn_zoom_in.clicked.connect(self.zoom_in)
        btn_zoom_out = QPushButton("缩小")
        btn_zoom_out.clicked.connect(self.zoom_out)
        btn_prev = QPushButton("上一张")
        btn_prev.clicked.connect(self.prev_image)
        btn_next = QPushButton("下一张")
        btn_next.clicked.connect(self.next_image)
        nav_layout.addWidget(btn_zoom_in)
        nav_layout.addWidget(btn_zoom_out)
        nav_layout.addWidget(btn_prev)
        nav_layout.addWidget(btn_next)
        layout.addLayout(nav_layout)

        # 图形视图
        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        self.view.setRenderHints(QPainter.Antialiasing | 
                                QPainter.SmoothPixmapTransform |
                                QPainter.TextAntialiasing)
        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setAlignment(Qt.AlignCenter)   # Ensure image is centered
        layout.addWidget(self.view)
        
        self.setLayout(layout)

    def load_images(self, rgb_path, ti_path):
        """加载并合成双视图图像（带智能适配）"""
        # 加载原始图像
        rgb = QPixmap(rgb_path)
        ti = QPixmap(ti_path)
        
        if rgb.isNull() or ti.isNull():
            return

        # 智能缩放计算
        max_height = 200
        spacing = 10
        max_total_width = 800

        # 保持宽高比缩放
        def scale_pixmap(p):
            return p.scaledToHeight(max_height, Qt.SmoothTransformation) if p.height() > max_height else p

        rgb_scaled = scale_pixmap(rgb)
        ti_scaled = scale_pixmap(ti)

        # 计算合成尺寸
        total_width = rgb_scaled.width() + ti_scaled.width() + spacing
        max_height_scaled = max(rgb_scaled.height(), ti_scaled.height())

        # 二次缩放保护
        if total_width > max_total_width:
            scale_ratio = max_total_width / total_width
            total_width = max_total_width
            rgb_scaled = rgb_scaled.scaled(
                int(rgb_scaled.width()*scale_ratio), 
                int(rgb_scaled.height()*scale_ratio), 
                Qt.KeepAspectRatio, Qt.SmoothTransformation
            )
            ti_scaled = ti_scaled.scaled(
                int(ti_scaled.width()*scale_ratio),
                int(ti_scaled.height()*scale_ratio),
                Qt.KeepAspectRatio, Qt.SmoothTransformation
            )
            max_height_scaled = max(rgb_scaled.height(), ti_scaled.height())

        # 创建合成图像
        combined = QPixmap(total_width, max_height_scaled)
        combined.fill(Qt.white)
        
        painter = QPainter(combined)
        # 垂直居中绘制
        y_rgb = (max_height_scaled - rgb_scaled.height()) // 2
        painter.drawPixmap(0, y_rgb, rgb_scaled)
        
        y_ti = (max_height_scaled - ti_scaled.height()) // 2
        painter.drawPixmap(rgb_scaled.width() + spacing, y_ti, ti_scaled)
        painter.end()

        # 缓存并更新视图
        self.current_pixmap = combined
        self._update_view()

    def _update_view(self):
        """统一更新视图的方法"""
        if self.current_pixmap:
            self.scene.clear()
            self.scene.addPixmap(self.current_pixmap)
            self.scene.setSceneRect(QRectF(self.current_pixmap.rect()))
            # Reset any transformations and center the view without scaling.
            self.view.resetTransform()
            self.view.setAlignment(Qt.AlignCenter)

    def _delayed_fit(self):
        """延迟执行视图适配"""
        if self.current_pixmap and not self.view.rect().isEmpty():
            self.view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
            self.scale_factor = self.view.transform().m11()

    def resizeEvent(self, event):
        """窗口尺寸变化时自动适配"""
        super().resizeEvent(event)
        self._delayed_fit()

    def zoom_in(self):
        self.view.scale(1.25, 1.25)
        self.scale_factor *= 1.25

    def zoom_out(self):
        self.view.scale(0.8, 0.8)
        self.scale_factor *= 0.8

    # 新增方法：设置图像列表并加载第一帧
    def set_images(self, rgb_list, ti_list):
        self.rgb_image_list = rgb_list
        self.ti_image_list = ti_list
        self.image_index = 0
        self.load_current_image()
    
    # 新增方法：加载当前索引的图像
    def load_current_image(self):
        if not self.rgb_image_list or not self.ti_image_list:
            return
        rgb_path = self.rgb_image_list[self.image_index]
        ti_path = self.ti_image_list[self.image_index]
        self.load_images(rgb_path, ti_path)
    
    # 新增方法：加载下一张图像
    def next_image(self):
        if self.rgb_image_list and self.image_index < len(self.rgb_image_list) - 1:
            self.image_index += 1
            self.load_current_image()
    
    # 新增方法：加载上一张图像
    def prev_image(self):
        if self.rgb_image_list and self.image_index > 0:
            self.image_index -= 1
            self.load_current_image()